package com.santoker.user.service.service.tp.wechat;

import com.santoker.baseservice.util.JSONUtil;
import com.santoker.baseservice.util.OkHttpHelper;
import com.santoker.user.service.service.tp.wechat.config.WeChatAbstractApi;
import com.santoker.user.service.service.tp.wechat.request.WeChatAppAccessTokenRequest;
import com.santoker.user.service.service.tp.wechat.request.WeChatAppUserInfoRequest;
import com.santoker.user.service.service.tp.wechat.response.WeChatAppAccessTokenResponse;
import com.santoker.user.service.service.tp.wechat.response.WeChatAppUserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WeChatApi extends WeChatAbstractApi {

    public WeChatAppAccessTokenResponse getAccessToken(String code) {
        WeChatAppAccessTokenRequest request = WeChatAppAccessTokenRequest.builder()
                .code(code)
                .build();
        log.info("request param: {} ", request.getParams());

        try {
            String url = weChatConfig.domain() + weChatConfig.accessToken();
            String response = OkHttpHelper.get(url, request.getParams())
                    .body().string();

            log.info("get response from url: {} response: {}", url, response);

            return JSONUtil.decodeJson(response, WeChatAppAccessTokenResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public WeChatAppUserInfoResponse getUserInfo(String accessToken, String openid) {
        WeChatAppUserInfoRequest request = WeChatAppUserInfoRequest.builder()
                .accessToken(accessToken)
                .openid(openid)
                .build();
        log.info("request param: {} ", request.getParams());

        try {
            String url = weChatConfig.domain() + weChatConfig.userInfo();
            String response = OkHttpHelper.get(url, request.getParams())
                    .body().string();

            log.info("get response from url: {} response: {}", url, response);

            return JSONUtil.decodeJson(response, WeChatAppUserInfoResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
